<template>
  <div class="exam-list">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-input v-model="searchQuery" placeholder="搜索考试名称" class="search-input" clearable @clear="handleSearch"
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleCreateExam">
        <el-icon>
          <Plus />
        </el-icon>
        创建考试
      </el-button>
    </div>

    <!-- 考试列表 -->
    <el-card class="exam-table">
      <el-table v-loading="loading" :data="examList" style="width: 100%" border>
        <el-table-column prop="index" min-width="80" label="序号" sortable/>
        <el-table-column prop="examName" label="考试名称" min-width="200" sortable/>
        <el-table-column prop="startTime" label="开始时间" min-width="155" sortable/>
        <el-table-column prop="endTime" label="结束时间" min-width="155" sortable/>
        <el-table-column prop="duration" label="考试时长(分钟)" min-width="150" sortable/>
        <el-table-column prop="examProcessStatus" label="考试状态" min-width="120" sortable>
          <template #default="{ row }">
            <el-tag :type="getExamProcessStatusType(row.examProcessStatus)">
              {{ row.examProcessStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="statusId" label="考生状态" min-width="120" sortable>
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.statusId)">
              {{ getStatusText(row.statusId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="160" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.examProcessStatus === '未开始'" type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button v-if="row.examProcessStatus === '未开始'" type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
            <el-button v-if="['考试中', '未开始'].includes(row.examProcessStatus) && row.statusId === 10000" type="danger"
              link @click="handleRegistration(row)">
              报名
            </el-button>
            <el-button v-if="row.examProcessStatus === '考试中' && [10001, 10003].includes(row.statusId)" type="success"
              link @click="handleStart(row)">
              开始考试
            </el-button>
            <el-button v-if="['已结束'].includes(row.examProcessStatus) && [10004, 10005].includes(row.statusId)"
              type="warning" link @click="handleViewResults(row)">
              查看成绩
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
      <span>确定要删除考试 "{{ currentExam?.name }}" 吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import { examApi } from "../../api/examApi";
import { getExamProcessStatusByDateRange, getExamProcessStatusType, getStatusTag, getStatusText } from "../../utils/utils";

const router = useRouter();
const loading = ref(false);
const examList = ref([]);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const deleteDialogVisible = ref(false);
const currentExam = ref(null);

// 获取考试列表
const getExamPage = async () => {
  loading.value = true;
  try {
    const res = await examApi.getExamPage({
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      examName: searchQuery.value,
    });
    examList.value = res.result.data;
    examList.value.forEach((o,index) => {
      o.examProcessStatus = getExamProcessStatusByDateRange(o.startTime, o.endTime);
      o.index = index + 1 + pageSize.value * (currentPage.value - 1);
    });
    total.value = res.result.total;
  } catch (error) {
    console.error("获取考试列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getExamPage();
};

// 创建考试
const handleCreateExam = () => {
  router.push("/exam/add");
};

// 编辑考试
const handleEdit = (row) => {
  router.push(`/exam/${row.examId}/edit`);
};

// 删除考试
const handleDelete = (row) => {
  currentExam.value = row;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  try {
    await examApi.deleteExam(currentExam.value.examId);
    ElMessage.success("删除成功");
    deleteDialogVisible.value = false;
    getExamPage();
  } catch (error) {
    console.error("删除考试失败:", error);
  }
};

// 查看成绩
const handleViewResults = (row) => {
  router.push(`/exam/${row.examId}/results`);
};
// 开始考试
const handleRegistration = async (row) => {
  try {
    await ElMessageBox.confirm(
      "确定要报名考试吗？",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    await examApi.registrationExam(row.examId);
    ElMessage.success("考试报名成功！");
    getExamPage();
  } catch (error) {
    if (error !== "cancel") {
      console.error("考试报名失败:", error);
    }
  }
};

// 开始考试
const handleStart = async (row) => {
  try {
    await ElMessageBox.confirm(
      "确定要开始考试吗？确定后考生可以进入考试。",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    ElMessage.success("考试已开始");
    router.push(`/do-exam/${row.examId}`);
  } catch (error) {
    if (error !== "cancel") {
      console.error("开始考试失败:", error);
    }
  }
};

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  getExamPage();
};

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getExamPage();
};

onMounted(() => {
  getExamPage();
});
</script>

<style scoped>
.exam-list {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.exam-table {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
